package com.hyphenate.easeui.mwidget.mutil;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Vibrator;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;

import androidx.core.content.FileProvider;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.easeui.R;
import com.hyphenate.easeui.mwidget.bean.AreaCodeBean;
import com.hyphenate.easeui.mwidget.bean.HYSBean;
import com.hyphenate.easeui.mwidget.bean.NianBean;
import com.hyphenate.easeui.mwidget.bean.ShengBean;
import com.hyphenate.easeui.mwidget.pickerview.builder.OptionsPickerBuilder;
import com.hyphenate.easeui.mwidget.pickerview.builder.TimePickerBuilder;
import com.hyphenate.easeui.mwidget.pickerview.listener.OnOptionsSelectListener;
import com.hyphenate.easeui.mwidget.pickerview.listener.OnTimeSelectListener;
import com.hyphenate.easeui.mwidget.pickerview.view.OptionsPickerView;
import com.hyphenate.easeui.mwidget.pickerview.view.TimePickerView;
import com.hyphenate.easeui.mwidget.wheelview.view.WheelView;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static android.content.Context.ACTIVITY_SERVICE;
import static android.content.Context.VIBRATOR_SERVICE;

public class MUtils {

    private static final int LOG_MAXLENGTH = 2000;

    public static void vibrate(Context ctx) {
        Vibrator vibrator = (Vibrator) ctx.getSystemService( VIBRATOR_SERVICE );
        vibrator.vibrate( 200 );
    }

    public static void showSingle(final Context ctx, final List<String> optionsItems, final OnOptionsSelectListener listener) {
        OptionsPickerView pvOptions = new OptionsPickerBuilder( ctx, listener )
                .setTitleBgColor( 0xffffffff )
                .setTextColorCenter( Color.BLACK ) //设置选中项文字颜色
                .setContentTextSize( 20 )
                .build();
        pvOptions.setPicker( optionsItems );
        pvOptions.show();
    }

    /**
     * 判断某一个类是否存在任务栈里面
     *
     * @return
     */
    public static boolean isExsitMianActivity(Activity act, Class<?> cls) {
        Intent intent = new Intent( act, cls );
        ComponentName cmpName = intent.resolveActivity( act.getPackageManager() );
        boolean flag = false;
        if (cmpName != null) { // 说明系统中存在这个activity
            ActivityManager am = (ActivityManager) act.getSystemService( ACTIVITY_SERVICE );
            List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks( 10 );
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.baseActivity.equals( cmpName )) { // 说明它已经启动了
                    flag = true;
                    break;  //跳出循环，优化效率
                }
            }
        }
        return flag;
    }

    /**
     * 获取状态栏高度
     *
     * @param context context
     * @return 状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        // 获得状态栏高度
        int resourceId = context.getResources().getIdentifier( "status_bar_height", "dimen", "android" );
        return context.getResources().getDimensionPixelSize( resourceId );
    }

    public static void installApkPath(Context ctx, String fileName) {
        File file = new File( fileName );
        if (!file.exists())
            return;
        Intent intent = new Intent( Intent.ACTION_VIEW );
        intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
        intent.putExtra( Intent.EXTRA_NOT_UNKNOWN_SOURCE, true ); //表明不是未知来源
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION );
            Uri contentUri = FileProvider.getUriForFile( ctx, ctx.getPackageName() + ".fileProvider", file );
            intent.setDataAndType( contentUri, "application/vnd.android.package-archive" );
        } else {
            intent.setDataAndType( Uri.fromFile( file ), "application/vnd.android.package-archive" );
        }
        ctx.startActivity( intent );
    }

    public static int getLocalVersion(Context ctx) {
        int localVersion = 0;
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo( ctx.getPackageName(), 0 );
            localVersion = packageInfo.versionCode;
//            LogUtil.d("TAG", "本软件的版本号。。" + localVersion);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    public static String getExt(String filename) {
        int index = filename.lastIndexOf( "." );

        if (index == -1) {
            return null;
        }
        String result = filename.substring( index + 1 );
        return result;
    }

    /**
     * 获取本地软件版本号名称
     */
    public static String getLocalVersionName(Context ctx) {
        String localVersion = "";
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo( ctx.getPackageName(), 0 );
            localVersion = packageInfo.versionName;
//            LogUtil.d("TAG", "本软件的版本号。。" + localVersion);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    public static String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader( new InputStreamReader(
                    assetManager.open( fileName ) ) );
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append( line );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public static TimePickerView getTimePicker(Context ctx, boolean filtWill, OnTimeSelectListener onTimeSelectListener) {
        TimePickerBuilder timePickerBuilder = new TimePickerBuilder( ctx, onTimeSelectListener )
                .setType( new boolean[]{true, true, true, false, false, false} )
                .isDialog( true ) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .setItemVisibleCount( 5 ) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier( 2.0f )
                .isAlphaGradient( true )
                .setDividerColor( 0xff4ccbbc )
                .setDividerType( WheelView.DividerType.WRAP );
        if (filtWill) {
            Calendar calendar = Calendar.getInstance();
            calendar.set( 1920, 1, 1 );
            timePickerBuilder.setRangDate( calendar, Calendar.getInstance() );
//            timePickerBuilder.
        }
        TimePickerView pvTime = timePickerBuilder
                .build();
        pvTime.setDate( Calendar.getInstance() );
        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM );

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams( params );

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations( R.style.picker_view_slide_anim );//修改动画样式
                dialogWindow.setGravity( Gravity.BOTTOM );//改成Bottom,底部显示
                dialogWindow.setDimAmount( 0.3f );
            }
        }
        return pvTime;
    }
    public static TimePickerView getHMSTimePicker(Context ctx, boolean filtWill, OnTimeSelectListener onTimeSelectListener) {
        TimePickerBuilder timePickerBuilder = new TimePickerBuilder( ctx, onTimeSelectListener )
                .setType( new boolean[]{true, true, true, true, true,false} )
                .isDialog( true ) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .setItemVisibleCount( 5 ) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier( 2.0f )
                .isAlphaGradient( true )
                .setDividerColor( 0xff4ccbbc )
                .setDividerType( WheelView.DividerType.WRAP );
        if (filtWill) {
            Calendar calendar = Calendar.getInstance();
            calendar.set( 1920, 1, 1 );
            timePickerBuilder.setRangDate( calendar, Calendar.getInstance() );
//            timePickerBuilder.
        }
        TimePickerView pvTime = timePickerBuilder
                .build();
        pvTime.setDate( Calendar.getInstance() );
        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM );

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams( params );

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations( R.style.picker_view_slide_anim );//修改动画样式
                dialogWindow.setGravity( Gravity.BOTTOM );//改成Bottom,底部显示
                dialogWindow.setDimAmount( 0.3f );
            }
        }
        return pvTime;
    }
    public static void showHBSJSelector(final Context ctx, final OnOptionsSelectListener listener) {
        final List<NianBean> options1Items = new ArrayList<>();
        final List<List<String>> options2Items = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            ArrayList<String> yueBeans = new ArrayList<>();
            NianBean e;
            if (i == 0) {
                e = new NianBean( "1年以下", yueBeans );
            } else {
                e = new NianBean( i < 4 ? i + "年" : "5年以上", yueBeans );
            }
            if (i < 4)
                for (int j = 0; j < 12; j++) {
                    if (i == 0 && j == 0)
                        e.yueBeans.add( "不满1月" );
//                    else {
//                        if (j == 0)
//                            e.yueBeans.add( "" );
                    else
                        e.yueBeans.add( j + "月" );
//                    }
                }
            else {
                e.yueBeans.add( "" );
            }
            options2Items.add( e.yueBeans );
            options1Items.add( e );
        }
        OptionsPickerView pvOptions = new OptionsPickerBuilder( ctx, listener )
                .setTitleText( "患病时长" )
                .setTitleBgColor( 0xffffffff )
                .setDividerColor( 0xff4ccbbc )
                .setDividerType( WheelView.DividerType.WRAP )
                .setTextColorCenter( Color.BLACK ) //设置选中项文字颜色
                .setContentTextSize( 20 )
                .build();
        pvOptions.setPicker( options1Items, options2Items );//二级选择器
        pvOptions.show();
    }

    public static void showHYS(final Context ctx, final OnOptionsSelectListener listener) {

        final List<HYSBean> options1Items = new ArrayList<>();
        HYSBean hysBean1 = new HYSBean( "未婚未育" );
        options1Items.add( hysBean1 );
        HYSBean hysBean2 = new HYSBean( "已婚未育" );
        options1Items.add( hysBean2 );
        HYSBean hysBean3 = new HYSBean( "已婚已育" );
        options1Items.add( hysBean3 );
        OptionsPickerView pvOptions = new OptionsPickerBuilder( ctx, listener )
                .setTitleText( "婚育史" )
                .setTitleBgColor( 0xffffffff )
                .setDividerColor( 0xff4ccbbc )
                .setDividerType( WheelView.DividerType.WRAP )
                .setTextColorCenter( Color.BLACK ) //设置选中项文字颜色
                .setContentTextSize( 20 )
                .build();
        pvOptions.setPicker( options1Items );
        pvOptions.show();
    }

    public static void showShengShiCodeSelector(final Context ctx, final OnOptionsSelectListener listener) {
        AsyncTask<Context, Integer, List<AreaCodeBean>> asyncTask = new AsyncTask<Context, Integer, List<AreaCodeBean>>() {
            @Override
            protected List<AreaCodeBean> doInBackground(Context... contexts) {
                List<AreaCodeBean> options1Items = new ArrayList<AreaCodeBean>();

                ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
                String jsonStr = new MUtils().getJson( contexts[0], "province_code.json" );//获取assets目录下的json文件数据
//     数据解析
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<List<AreaCodeBean>>() {
                }.getType();
                List<AreaCodeBean> shengList = gson.fromJson( jsonStr, type );

//     把解析后的数据组装成想要的list
                Map<String, List<AreaCodeBean>> datas = new HashMap<>();
                List<AreaCodeBean> shengs = null;
                if (shengList != null) {
                    for (AreaCodeBean tmp : shengList) {
                        if (datas.get( tmp.getParentId() ) == null) {
                            datas.put( tmp.getParentId(), new ArrayList<AreaCodeBean>() );
                        }
                        ((ArrayList<AreaCodeBean>) datas.get( tmp.getParentId() )).add( tmp );
                    }
                    shengs = datas.get( "100000" );
                    if (shengs != null) {
                        for (AreaCodeBean sheng : shengs) {
                            sheng.setSubList( datas.get( sheng.id ) );
                        }
                    }
                }
//                options1Items = shengList;
                return shengs;
            }

            @Override
            protected void onPostExecute(List<AreaCodeBean> shengList) {
                super.onPostExecute( shengList );
                e( "data", new Gson().toJson( shengList ) );
                if (shengList != null && shengList.size() > 0) {
                    final List<AreaCodeBean> options1Items = shengList;
                    final ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
                    for (int i = 0; i < shengList.size(); i++) {
                        ArrayList<String> cityList = new ArrayList<>();
                        ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();
                        for (int c = 0; c < shengList.get( i ).getSubList().size(); c++) {
                            String cityName = shengList.get( i ).getSubList().get( c ).name;
                            cityList.add( cityName );
//                            ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表
//                            if (shengList.get( i ).getSubList().get( c ).area == null || shengList.get( i ).city.get( c ).area.size() == 0) {
//                                city_AreaList.add( "" );
//                            } else {
//                                city_AreaList.addAll( shengList.get( i ).city.get( c ).area );
//                            }
//                            province_AreaList.add( city_AreaList );
                        }
                        /**
                         * 添加城市数据
                         */

                        options2Items.add( cityList );
                    }
                    OptionsPickerView pvOptions = new OptionsPickerBuilder( ctx, listener )
                            .setTitleText( "选择地区" )
                            .setTitleBgColor( 0xffffffff )
                            .setDividerColor( 0xff4ccbbc )
                            .setDividerType( WheelView.DividerType.WRAP )
                            .setTextColorCenter( Color.BLACK ) //设置选中项文字颜色
                            .setContentTextSize( 20 )
                            .build();
                    pvOptions.setPicker( options1Items, options2Items );//二级选择器
                    pvOptions.show();
                }
            }
        };
        asyncTask.execute( ctx );
    }

    public static void e(String TAG, String msg) {
        int strLength = msg.length();
        int start = 0;
        int end = LOG_MAXLENGTH;
        for (int i = 0; i < 100; i++) {
            //剩下的文本还是大于规定长度则继续重复截取并输出
            if (strLength > end) {
                Log.e( TAG + i, msg.substring( start, end ) );
                start = end;
                end = end + LOG_MAXLENGTH;
            } else {
                Log.e( TAG, msg.substring( start, strLength ) );
                break;
            }
        }
    }

    public static void showShengShiSelector(final Context ctx, final OnOptionsSelectListener listener) {
        AsyncTask<Context, Integer, List<ShengBean>> asyncTask = new AsyncTask<Context, Integer, List<ShengBean>>() {
            @Override
            protected List<ShengBean> doInBackground(Context... contexts) {
                List<ShengBean> options1Items = new ArrayList<ShengBean>();

                ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
                String jsonStr = new MUtils().getJson( contexts[0], "province.json" );//获取assets目录下的json文件数据
//     数据解析
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<List<ShengBean>>() {
                }.getType();
                List<ShengBean> shengList = gson.fromJson( jsonStr, type );

//     把解析后的数据组装成想要的list
                options1Items = shengList;
                return options1Items;
            }

            @Override
            protected void onPostExecute(List<ShengBean> shengList) {
                super.onPostExecute( shengList );
                if (shengList != null && shengList.size() > 0) {
                    final List<ShengBean> options1Items = shengList;
                    final ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
                    for (int i = 0; i < shengList.size(); i++) {
                        ArrayList<String> cityList = new ArrayList<>();
                        ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();
                        for (int c = 0; c < shengList.get( i ).city.size(); c++) {
                            String cityName = shengList.get( i ).city.get( c ).name;
                            cityList.add( cityName );
                            ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表
                            if (shengList.get( i ).city.get( c ).area == null || shengList.get( i ).city.get( c ).area.size() == 0) {
                                city_AreaList.add( "" );
                            } else {
                                city_AreaList.addAll( shengList.get( i ).city.get( c ).area );
                            }
                            province_AreaList.add( city_AreaList );
                        }
                        /**
                         * 添加城市数据
                         */

                        options2Items.add( cityList );
                    }
                    OptionsPickerView pvOptions = new OptionsPickerBuilder( ctx, listener )
                            .setTitleText( "选择地区" )
                            .setTitleBgColor( 0xffffffff )
                            .setDividerColor( 0xff4ccbbc )
                            .setDividerType( WheelView.DividerType.WRAP )
                            .setTextColorCenter( Color.BLACK ) //设置选中项文字颜色
                            .setContentTextSize( 20 )
                            .build();
                    pvOptions.setPicker( options1Items, options2Items );//二级选择器
                    pvOptions.show();
                }
            }
        };
        asyncTask.execute( ctx );
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    // md5加密 32位小写
    public static String Md5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance( "MD5" );
            md.update( sourceStr.getBytes() );
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer( "" );
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append( "0" );
                buf.append( Integer.toHexString( i ) );
            }
            result = buf.toString();
            System.out.println( "result: " + result );//32位的加密
            System.out.println( "result: " +
                    buf.toString().substring( 8, 24 ) );//16位的加密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }

    //系统剪贴板-获取:
    public static String getCopy(Context context) {
        // 获取系统剪贴板
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService( Context.CLIPBOARD_SERVICE );
        // 返回数据
        ClipData clipData = clipboard.getPrimaryClip();
        if (clipData != null && clipData.getItemCount() > 0) {
            // 从数据集中获取（粘贴）第一条文本数据
            return clipData.getItemAt( 0 ).getText().toString();
        }
        return null;
    }

    public static String stampToDateyyyyMMddHHmm(Long s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm" );
        long lt = s * 1000;
        Date date = new Date( lt );
        res = simpleDateFormat.format( date );
        return res;
    }

    public static String stampToDateXXFormat(Long s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm" );
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat( "HH:mm" );
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat( "yy-MM-dd" );
        long lt = s * 1000;
        Date date = new Date( lt );
        Date date2 = new Date( System.currentTimeMillis() );
        Date tmpD = new Date( date.getTime() );
        date2.setHours( 0 );
        date2.setMinutes( 0 );
        date2.setSeconds( 0 );
        tmpD.setHours( 0 );
        tmpD.setMinutes( 0 );
        tmpD.setSeconds( 0 );
        int tmp = 86400000;

        long day1 = tmpD.getTime() / tmp;
        long day2 = date2.getTime() / tmp;

        if (day2 - day1 == 0) {
            return simpleDateFormat1.format( date );
        } else if (day2 - day1 == 1) {
            return "昨天";
        } else {
            return simpleDateFormat2.format( date );
        }

    }

    public static boolean isYesToday(Date date) {
        SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd" );

        Date date2 = new Date( System.currentTimeMillis() );
        date2.setHours( 0 );
        date2.setMinutes( 0 );
        date2.setSeconds( 0 );
        int tmp = 86400000;

        long day1 = date.getTime() / tmp;
        long day2 = date2.getTime() / tmp;

        if (day2 - day1 == 1) {
            return true;
        } else {
            return false;
        }
    }

    //时间戳转化为时间（毫秒）
    public static String getDateToString(long milSecond) {
        try {
            String pattern = "yyyy-MM-dd HH:mm:ss";
            Date date = new Date( milSecond * 1000 );
            SimpleDateFormat format = new SimpleDateFormat( pattern );
            return format.format( date );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String stampToDateyyyyMMdd(Long s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy年MM月dd日" );
        long lt = s * 1000;
        Date date = new Date( lt );
        res = simpleDateFormat.format( date );
        return res;
    }

    public static String getAppName(int pID, Application appContext) {
        String processName = null;
        ActivityManager am = (ActivityManager) appContext.getSystemService( ACTIVITY_SERVICE );
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = appContext.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }

    public static void shareUrl(Context ctx, String str) {

        Intent shareIntent = new Intent();
        shareIntent.setAction( Intent.ACTION_SEND );
        shareIntent.setType( "text/html" );
        shareIntent.putExtra( Intent.EXTRA_TEXT, str );//分享出去的内容
        ctx.startActivity( Intent.createChooser( shareIntent, "选择分享的应用" ) );
    }

    public static int getAgeByBirth(Date birthDay) throws ParseException {
        int age = 0;
        Calendar cal = Calendar.getInstance();
        if (cal.before( birthDay )) { //出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!" );
        }
        int yearNow = cal.get( Calendar.YEAR );  //当前年份
        int monthNow = cal.get( Calendar.MONTH );  //当前月份
        int dayOfMonthNow = cal.get( Calendar.DAY_OF_MONTH ); //当前日期
        cal.setTime( birthDay );
        int yearBirth = cal.get( Calendar.YEAR );
        int monthBirth = cal.get( Calendar.MONTH );
        int dayOfMonthBirth = cal.get( Calendar.DAY_OF_MONTH );
        age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age;
    }

    private static Calendar zeroFromHour(long milliseconds) {
        Calendar calendar = Calendar.getInstance(); // 获得一个日历

        calendar.setTimeInMillis( completMilliseconds( milliseconds ) );
        zeroFromHour( calendar );
        return calendar;
    }

    /**
     * 将时，分，秒，以及毫秒值设置为0
     *
     * @param calendar
     */
    private static void zeroFromHour(Calendar calendar) {
        calendar.set( Calendar.HOUR_OF_DAY, 0 );
        calendar.set( Calendar.MINUTE, 0 );
        calendar.set( Calendar.SECOND, 0 );
        calendar.set( Calendar.MILLISECOND, 0 );
    }

    /**
     * 由于服务器返回的是10位，手机端使用需要补全3位
     *
     * @param milliseconds
     * @return
     */
    private static long completMilliseconds(long milliseconds) {
        String milStr = Long.toString( milliseconds );
        if (milStr.length() == 10) {
            milliseconds = milliseconds * 1000;
        }
        return milliseconds;
    }

    /**
     * 是否是 今天
     *
     * @param timStap 时间毫秒
     * @return
     */
    public static boolean isToday(long timStap) {
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
        Date date = new Date( timStap );
        if (sdf.format( date ).equals( sdf.format( new Date() ) )) {  //今天
            return true;
        }
        return false;
    }

    /**
     * 最终调用方法
     *
     * @param timeStamp
     * @return
     */

    public static String getWhatDay(long timeStamp) {
        Calendar cal = zeroFromHour( timeStamp );
        String whatDay = "";
        if (cal.get( Calendar.DAY_OF_WEEK ) == Calendar.SATURDAY) {
            whatDay = "星期六";
        }
        if (cal.get( Calendar.DAY_OF_WEEK ) == Calendar.SUNDAY) {
            whatDay = "星期日";
        }
        if (cal.get( Calendar.DAY_OF_WEEK ) == Calendar.MONDAY) {
            whatDay = "星期一";
        }
        if (cal.get( Calendar.DAY_OF_WEEK ) == Calendar.TUESDAY) {
            whatDay = "星期二";
        }
        if (cal.get( Calendar.DAY_OF_WEEK ) == Calendar.WEDNESDAY) {
            whatDay = "星期三";
        }
        if (cal.get( Calendar.DAY_OF_WEEK ) == Calendar.THURSDAY) {
            whatDay = "星期四";
        }
        if (cal.get( Calendar.DAY_OF_WEEK ) == Calendar.FRIDAY) {
            whatDay = "星期五";
        }
        return whatDay;
    }


}